package com.cdu.controller;

import com.cdu.commons.*;
import com.cdu.pojo.dto.CartPageQueryDTO;
import com.cdu.pojo.dto.TokenUser;
import com.cdu.pojo.vo.CartVO;
import com.cdu.service.CartService;
import com.cdu.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.JstlUtils;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/cart")
@Slf4j
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("/add")
    public R<String> addCart(Integer productId,Integer price, HttpServletRequest request) {
        //解析token，获取用户信息，然后将商品加入购物车
        log.info("加入购物车成功，商品id：{}", productId);
        String token = request.getHeader(MallConstants.TOKEN_SIGN);

        if (token == null){
            throw new ServiceException("请先登录", ServiceCode.NO_LOGIN_CODE);
        }
        //解析token，获取用户信息
        TokenUser tokenUser = JwtUtils.getTokenUser(token);

        //进入业务层；
        //调用service层，将商品加 入购物车；
        cartService.addCart(productId,price, tokenUser);


        //返回成功信息

        return R.ok("加入购物车成功");
    }

    @PostMapping("/page")
    public R<PageR> showCart(CartPageQueryDTO cartPageQueryDTO,HttpServletRequest request){
        log.info("查询购物车成功");
        String token = request.getHeader(MallConstants.TOKEN_SIGN);

        if (token == null){
            throw new ServiceException("请先登录", ServiceCode.NO_LOGIN_CODE);
        }
        //解析token，获取用户信息
        TokenUser tokenUser = JwtUtils.getTokenUser(token);
        PageR pageR=cartService.show(cartPageQueryDTO,tokenUser);
        return new R<PageR>().ok("查询购物车成功",pageR);
    }

    @PostMapping("/sub")
    public R subCart(Integer productId,HttpServletRequest request){
        String token = request.getHeader(MallConstants.TOKEN_SIGN);

        if (token == null){
            throw new ServiceException("请先登录", ServiceCode.NO_LOGIN_CODE);
        }
        //解析token，获取用户信息
        TokenUser tokenUser = JwtUtils.getTokenUser(token);
        cartService.subCart(productId,tokenUser);
        return R.ok("操作成功");
    }
}
